<style>
    .companyFormPhotos{
        /* margin-left:140px; */
        line-height: 38px;
        float: left;
    }
    .companyFormPhotos img{
        cursor: pointer;
        height: 38px;
        width: auto;
        max-width: 200px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">客户名称</label>
                                    <div class="layui-input-inline mr0">
                                        <select id="customerNameId" name="customerNameId" lay-filter="customerNameId"
                                                lay-verify="required" required>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="warehouseProductTable" lay-filter="warehouseProductTable"></table>
        </div>
    </div>
</div>
<script type="text/html" id="warehouseBillForm">
    <form lay-filter="warehouseBillForm" class="layui-form model-form">
        <div class="layui-form-item">
            <label class="layui-form-label">结算金额</label>
            <div class="layui-input-block">
                <input name="amount" id="amount" placeholder="请输入结算金额" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div  class="layui-form-item" >
            <label class="layui-form-label">上传附件</label>
            <div class="layui-input-block">
                <div id="contractFileUrlPath" class="companyFormPhotos"></div>
                <div id="btnContractFileUrl" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传PDF文件</div>
                <input  id="contractFileUrl" name="contractFileUrl" type="hidden" class="layui-input" lay-verify=""/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="warehouseBillFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>
<!-- 表格操作列 -->
<script type="text/html" id="warehouseProductTableBar">
    {{# if(d.billStatus == '0'){ }}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="settlement">结算</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="paymentVoucher">付款凭证</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="invoice">发票</a>
    {{# } }}
    <a class="layui-btn layui-btn layui-btn-xs" lay-event="info">详情</a>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin','upload','tableTreeDj','config'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;

        // 渲染表格
        var insTb = table.render({
            elem: '#warehouseProductTable',
            url: config.base + 'warehouse/warehouse/admin/bill/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'}
                ,{field: 'customerName', title: '客户名称', align: 'center'}
                ,{field: 'billPeriod',title: '账单月份', align: 'center'}
                ,{field: 'totalBills', title: '产品数量', align: 'center'}
                ,{field: 'billPrice', title: '合计金额' , align: 'center'}
                ,{field: 'totalDetailPrice', title: '预计支付金额' , align: 'center'}
                ,{field: 'billStatusDesc', title: '结算状态' , align: 'center'}
                ,{align: 'center', toolbar: '#warehouseProductTableBar', title: '操作', width: 300, fixed: 'right'}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if(menuButton.indexOf("搜索") == -1){
                //     $('.layui-form.toolbar').remove();
                // }
                // if(menuButton.indexOf("修改") == -1){
                //     $("[lay-event='edit']").remove();
                // }
                // if(menuButton.indexOf("删除") == -1){
                //     $("[lay-event='del']").remove();
                // }
            }
        });

        // 工具条点击事件
        table.on('tool(warehouseProductTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'info') { //详情
                admin.req(
                    "warehouse/warehouse/admin/bill/selectBill",
                    { id: data.id },
                    (res) => {
                        if (res.code === 200) {
                            openFormFun("detail", res.data);
                        }
                    }
                );
            } else if (obj.event === 'settlement') { // 结算
                settlement(data);
            }else if(obj.event ==='invoice'){  //发票
                admin.req(
                    "warehouse/warehouse/admin/bill/selectBill",
                    { id: data.id },
                    (res) => {
                        if (res.code === 200) {
                            return
                            openinvoice( res.data);
                        }
                    }
                );
            }
        });
        /*发票*/
        function openinvoice(data){
            admin.formOpen({
                area: "90%",
                offset: "10%",
                title: "添加采购订单发票信息",
                path: "components/warehouse/bill/warehouseBillInvoice.html",
                success: function () {
                    parentData.data = [data];
                }
            });
        }
        //详情
        function openFormFun(eventName, data) {
            admin.formOpen({
                area: "90%",
                offset: "10%",
                title: "配置订单物料信息",
                path: "components/warehouse/bill/warehouseBillForm.html",
                success: function () {
                    parentData.eventName = eventName;
                    parentData.data = data;
                }
            });
        }
        function settlement(data){
            admin.formOpen({
                type: 1,
                area: ['40%', '30%'],
                offset: '65px',
                title: '结算',
                content: $('#warehouseBillForm').html(),
                success: function () {
                    // 表单提交事件
                    form.on('submit(warehouseBillFormSubmit)', function (d) {

                        admin.req('warehouse/warehouse/admin/bill/settlement', {id:data.id,amount:d.field.amount,billVoucherUrl:d.field.contractFileUrl}, function (res) {
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload("warehouseProductTable");
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'GET');
                        return false;
                    });
                    $('#btnContractFileUrl').click(uploadImg('btnContractFileUrl','contractFileUrlPath','contractFileUrl'));

                }
            });
        }

        admin.reqSync('enterprise/sell/admin/customersInfo/list', {'limit':9999}, function (res) {
            layer.closeAll('loading');
            if (res.code == 200) {
                loadSelectHtml(res.data, "请选客户信息", "customerNameId",1);
            }
        }, 'GET');


        //监听排序
        table.on('sort(warehouseProductTable)', function(obj){
            table.reload('warehouseProductTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });
        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });


        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 1) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].customerName}</option>`;
                } else {
                    html += `<option value='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }
        // 上传图片
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: '#' + _elem
                , url: config.upload_url + 'uploadFile'
                , data: {}
                , accept: 'file'
                , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                , headers: { Authorization: 'Bearer ' + config.getToken() }
                , done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", { icon: 1 });
                        let imagUrl = res.data.url;
                        $('#' + pathId).html('<img src="' +imagUrl + '"/>');
                        $('#' + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace('member/login.html');
                    } else {
                        layer.msg(res.msg || "上传失败", { icon: 2 });
                    }
                }
            });
        }
    });
</script>